import pandas as pd
from matplotlib import pyplot as plt
import numpy as np

def normalize_list(lst):
    amin, amax = min(lst), max(lst)
    for i, val in enumerate(lst):
        lst[i] = (val-amin) / (amax-amin)
    return lst

def main ():
    # Load IV, DV, and CV
    iv = pd.read_csv("iv.csv")
    iv_grouped = pd.read_csv("iv_grouped.csv")
    dv = pd.read_csv("dv.csv")
    cv = pd.read_csv("cv.csv")
    # create variables for every observation
    iv["constant"] = 1
    iv["source"] = ""
    iv["dv"] = 0.0
    iv["dv_lead"] = 0.0
    iv["casualties"] = 0.0
    iv["election"] = 0.0
    iv["missions_un_dummy"] = 0.0
    iv["missions_eu_dummy"] = 0.0
    iv["missions_nato_dummy"] = 0.0
    # iterate over every observation and assign variable value
    for index, row in iv.iterrows():
        year_index = row["year"] - 1990
        iv.loc[index, "source"] = row["source_id"].split("-")[0]
        iv.loc[index, "dv"] = dv.loc[year_index, "dv_norm"]
        iv.loc[index, "dv_lead"] = dv.loc[year_index, "dv_norm_lead"]
        iv.loc[index, "casualties"] = cv.loc[year_index, "casualties"]
        iv.loc[index, "election"] = cv.loc[year_index, "election"]
        iv.loc[index, "missions_un_dummy"] = cv.loc[year_index, "missions_un_dummy"]
        iv.loc[index, "missions_eu_dummy"] = cv.loc[year_index, "missions_eu_dummy"]
        iv.loc[index, "missions_nato_dummy"] = cv.loc[year_index, "missions_nato_dummy"]
    # export df for SPSS 
    iv.rename(columns={"Unnamed: 0":"id"}, inplace=True)
    iv.to_csv("results.csv", index = False)
    # create lists for figure
    years = list(range(1990,2018))
    sc = iv_grouped["score"]
    dv = dv["dv_norm"]
    # create figure
    fig, ax1 = plt.subplots(figsize=(14,6))
    linewidth = 1
    fontsize = 16
    color = 'black'
    ax1.set_ylabel('Strategic Culture', fontsize=fontsize, color=color)
    ax1.plot(years, sc, label="Strategic Culture", linewidth=linewidth, color=color)
    ax1.tick_params(axis='y', labelcolor=color, labelsize=fontsize)
    ax1.set(ylim=(-1.05, 1.05),xlim=(1989.75,2017.25))
    ax1.tick_params(axis="x", labelcolor=color, labelsize=fontsize)
    ax2 = ax1.twinx()
    color = 'black'
    ax2.set_ylabel('Strategic Behavior', fontsize=fontsize, color=color)
    ax2.plot(years, dv, label="Strategic Behavior", color=color, linewidth=linewidth, linestyle="--")
    ax2.tick_params(axis='y', labelcolor=color, labelsize=fontsize)
    fig.tight_layout()  
    fig.legend(loc=2, bbox_to_anchor=(0.097,0.95), fontsize=fontsize)
    plt.show()

if __name__ == "__main__":
    main()